<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

	public function index() {
		$cn_bing = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';
		$background = '';

		$expire_at = mktime(0, 0, 0, date("m"), date("d")+1, date("Y"));
		$this->load->driver('cache');
		$bing_background_ckey = 'bing_background_ckey';
		$background = $this->cache->file->get($bing_background_ckey);

		if (empty($background)) {
			$ret = curlTool($cn_bing);
			if ($ret) {
				$data = json_decode($ret, true);
				$background = isset($data['images'][0]['url']) ? $data['images'][0]['url'] : '';
				$this->cache->file->save($bing_background_ckey, $background, $expire_at-time());
			}
		}

		$this->_data['background'] = $background;
		$this->load->view('admin/login.html', $this->_data);
	}

	public function login_in() {
		if (!isset($_SESSION)) {
			session_start();
		}

		$this->load->model('admin_model', 'admin');

		$username = $this->input->post('username');

		$passwd = md5($this->input->post('passwd'));
		$user_data = $this->admin->check($username);

		if (!$user_data || $passwd != $user_data['password']) {
			$this->session->set_tempdata('error', '用户名或密码错误', 5);
			redirect('admin/login');
		}

		$array = array(
			'uid' => $user_data['uid'],
			'username'=> $user_data['username'],
			'gid' => $user_data['gid'],
		);
		
		$this->session->set_userdata( $array );
		redirect('admin/rules');
	}

	public function logout() {
		$this->session->sess_destroy();
		redirect('admin/login');
	}


}